<template>
  <div class="term-list">
    <nav-header></nav-header>
    <div class="zh-table">
      <div class="zh-table-contents">
        <div class="current-year">当前学年</div>
        <el-table
          :data="currentListData"
          :span-method="objectSpanMethod"
          border
          max-height="600"
          style="width: 100%"
        >
          <el-table-column
            prop="year"
            label="学年"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop=""
            label="学期"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span v-if="scope.row.semester === 1">{{
                "第一学期"
              }}</span>
              <span v-if="scope.row.semester === 2">{{
                "第二学期"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="start_time"
            label="开始日期"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="end_time"
            label="结束日期"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="weeks"
            label="教学周"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop=""
            label="操作"
            align="center"
            width="150"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-button
                @click="
                  editCurrentYear(scope.$index, scope.row, 'current-edit')
                "
                type="text"
                >编辑</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <hr
          style="height: 1px; border: none; border-top: 1px solid lightgray; margin-top: 40px;"
        />
        <div class="non-start-year">
          <div>未开始学年</div>
          <div>
            <el-button type="primary" @click="addYear('add')"
              >添加学年</el-button
            >
          </div>
        </div>
        <el-table
          :data="listData"
          :span-method="objectSpanMethod"
          border
          max-height="600"
          style="width: 100%"
        >
          <el-table-column
            prop="year"
            label="学年"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop=""
            label="学期"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span v-if="scope.row.semester === 1">{{ "第一学期" }}</span>
              <span v-if="scope.row.semester === 2">{{ "第二学期" }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="start_time"
            label="开始日期"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="end_time"
            label="结束日期"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="weeks"
            label="教学周"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop=""
            label="操作"
            align="center"
            width="150"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-button
                @click="editRow(scope.$index, scope.row, 'edit')"
                type="text"
                >编辑</el-button
              >
              <el-button
                @click="delRow(scope.row)"
                type="text"
                class="delete-button"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="table-pagination" v-show="total_number > 5">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="listParam.page_index"
            :page-sizes="[6, 12, 18, 24]"
            :page-size="listParam.page_size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total_number"
          >
          </el-pagination>
          <div class="pagination-button">
            <el-button
              @click="getList"
              type="primary"
              icon="el-icon-refresh"
              circle
              title="刷新数据"
              size="mini"
            >
            </el-button>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="cancel"
      :title="editTitle"
      :visible.sync="isShowEdit"
      width="450px"
      class="current-form"
    >
      <div
        v-if="editFlag === 2"
        style="font-size: 18px; font-weight: bold; margin-bottom: 10px;"
      >
        {{ editForm.academicYear }}
      </div>
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="rules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item
          label="学年："
          v-if="editFlag !== 2"
          class="year-title"
          prop="academicYear"
        >
          <el-select v-model="editForm.academicYear" placeholder="请选择学年">
            <el-option
              v-for="item in yearData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="第一学期"
          class="edit-semester-title"
        ></el-form-item>
        <el-form-item label="开始日期：" prop="firstStartTime">
          <el-date-picker
            v-model="editForm.firstStartTime"
            type="date"
            @change="changetime('1', '1')"
            placeholder="选择开始日期"
            :disabled="isTimeDisabled(editForm.firstStartTime)"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期：" prop="firstEndTime">
          <el-date-picker
            v-model="editForm.firstEndTime"
            type="date"
            @change="changetime('1', '2')"
            placeholder="选择结束日期"
            :disabled="isTimeDisabled(editForm.firstEndTime)"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="周数：">
          <span>{{ editForm.firstWeek }}</span>
        </el-form-item>
        <el-form-item
          label="第二学期"
          class="edit-semester-title"
        ></el-form-item>
        <el-form-item label="开始日期：" prop="secondStartTime">
          <el-date-picker
            v-model="editForm.secondStartTime"
            type="date"
            @change="changetime('2', '1')"
            placeholder="选择开始日期"
            :disabled="isTimeDisabled(editForm.secondStartTime)"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期：" prop="secondEndTime">
          <el-date-picker
            v-model="editForm.secondEndTime"
            type="date"
            @change="changetime('2', '2')"
            placeholder="选择结束日期"
            :disabled="isTimeDisabled(editForm.secondEndTime)"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="周数：">
          <span>{{ editForm.secondWeek }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="saveInfo('editForm')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      isShowEdit: false,
      editFlag: 1, // 1 添加 || 2 当前学年编辑 || 3 未来学年编辑
      total_number: 0,
      password: null,
      editTitle: "提示",
      listData: [],
      currentListData: [],
      yearData: [],
      loading: {
        status: false,
        txt: "获取数据..."
      },
      listParam: {
        page_index: 1,
        page_size: 5
      },
      editForm: {
        academicYear: null,
        firstid: null,
        firstWeek: 0,
        firstStartTime: null,
        firstEndTime: null,
        secondid: null,
        secondWeek: 0,
        secondStartTime: null,
        secondEndTime: null
      },
      rules: {
        academicYear: [
          { required: true, message: "请选择学年", trigger: "change" }
        ],
        firstStartTime: [{ validator: this.validatorStart, trigger: "change" }],
        firstEndTime: [{ validator: this.validatorStart, trigger: "change" }],
        secondStartTime: [{ validator: this.validatorEnd, trigger: "change" }],
        secondEndTime: [{ validator: this.validatorEnd, trigger: "change" }]
      }
    };
  },
  created() {
    this.getCurrentList();
    this.getList();
    this.getYearData();
  },
  methods: {
    addYear(val) {
      this.isShowEdit = true;

      if (val === "add") {
        this.editTitle = "新建学年";
        this.editFlag = 1;
        this.editForm.academicYear = null;
        this.editForm.firstid = null;
        this.editForm.firstWeek = 0;
        this.editForm.firstStartTime = "";
        this.editForm.firstEndTime = "";
        this.editForm.secondid = null;
        this.editForm.secondWeek = 0;
        this.editForm.secondStartTime = "";
        this.editForm.secondEndTime = "";

        setTimeout(() => {
          this.$refs["editForm"].clearValidate();
        }, 0);
      }
    },
    getList() {
      let success = data => {
        this.listData = [];
        let result = deep_clone(data.data);

        for (let k in result) {
          let temp = result[k];

          if (Array.isArray(temp)) {
            temp.forEach(item => {
              this.listData.push(item);
            });
          }
        }

        if (this.listData.length > 0) {
          this.listData.forEach(item => {
            item.year = item.start_year + " - " + item.end_year + " 学年";
            item.start_time = item.start_time.substr(0, 10);
            item.end_time = item.end_time.substr(0, 10);
          });
        }
      };
      let fail = data => {
        this.$message.error(data.msg);
      };

      this.$ajax.get("api/term/get_future_term", {
        params: this.listParam,
        func: { success: success, fail: fail }
      });
    },
    getCurrentList() {
      let success = data => {
        this.currentListData = deep_clone(data.data);

        if (this.currentListData.length > 0) {
          this.currentListData.forEach(item => {
            item.year = item.start_year + " - " + item.end_year + " 学年";
            item.start_time = item.start_time.substr(0, 10);
            item.end_time = item.end_time.substr(0, 10);
          });
        }
      };
      let fail = data => {
        this.$message.error(data.msg);
      };

      this.$ajax.get("api/term/get_now_term_year", {
        params: {},
        func: { success: success, fail: fail }
      });
    },
    saveInfo(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.isShowEdit = false;

          let success = data => {
            this.$message.success(data.msg);
            this.getCurrentList();
            this.getList();
          };
          let fail = data => {
            this.$message.error(data.msg);
          };

          let arr = [];
          let temp = [];

          if (this.editFlag === 1 || this.editFlag === 3) {
            temp = this.yearData[
              parseInt(this.editForm.academicYear)
            ].label.split(" - ");
          } else if (this.editFlag === 2) {
            temp = this.editForm.academicYear.split(" - ");
          }

          let temp2 = temp[1].split(" ");

          arr.push({
            id: this.editForm.firstid,
            start_year: temp[0],
            end_year: temp2[0],
            semester: 1,
            start_time: this.editForm.firstStartTime,
            end_time: this.editForm.firstEndTime
          });
          arr.push({
            id: this.editForm.secondid,
            start_year: temp2[0],
            end_year: temp2[0],
            semester: 2,
            start_time: this.editForm.secondStartTime,
            end_time: this.editForm.secondEndTime
          });

          if (this.editFlag === 1) {
            this.$ajax.post(
              "api/term/term",
              { arr: arr },
              { func: { success: success, fail: fail } }
            );
          } else if (this.editFlag === 2 || this.editFlag === 3) {
            arr.forEach(item => {
              item.password = this.password;
            });

            this.$ajax.put(
              "api/term/term",
              { arr: arr },
              { func: { success: success, fail: fail } }
            );
          }
        } else {
          return false;
        }
      });
    },
    editCurrentYear(index, obj, val) {
      this.isShowEdit = true;
      let nexObj = this.currentListData[index + 1];

      if (val === "current-edit") {
        this.editTitle = "学期修改";
        this.editFlag = 2;
        this.editForm.academicYear = obj.year;
        this.password = obj.password;
        this.editForm.firstid = obj.id;
        this.editForm.firstWeek = obj.weeks;
        this.editForm.firstStartTime = obj.start_time;
        this.editForm.firstEndTime = obj.end_time;
        this.editForm.secondid = nexObj.id;
        this.editForm.secondWeek = nexObj.weeks;
        this.editForm.secondStartTime = nexObj.start_time;
        this.editForm.secondEndTime = nexObj.end_time;

        if (this.$refs["editForm"]) {
          this.$refs["editForm"].clearValidate();
        }
      }
    },
    editRow(index, obj, val) {
      this.isShowEdit = true;
      let nexObj = this.listData[index + 1];

      if (val === "edit") {
        let temp = null;
        this.yearData.forEach(item => {
          if (item.label === obj.year) {
            temp = item.value;
          }
        });

        this.editTitle = "编辑学年";
        this.editFlag = 3;
        this.password = obj.password;
        this.editForm.academicYear = temp;
        this.editForm.firstid = obj.id;
        this.editForm.firstWeek = obj.weeks;
        this.editForm.firstStartTime = obj.start_time;
        this.editForm.firstEndTime = obj.end_time;
        this.editForm.secondid = nexObj.id;
        this.editForm.secondWeek = nexObj.weeks;
        this.editForm.secondStartTime = nexObj.start_time;
        this.editForm.secondEndTime = nexObj.end_time;

        if (this.$refs["editForm"]) {
          this.$refs["editForm"].clearValidate();
        }
      }
    },
    delRow(obj) {
      let yes = data => {
        this.delete(obj);
      };
      let cancel = data => {};
      this.e_confirm({ yes: yes, cancel: cancel, txt: "确定将该学年删除吗？" });
    },
    delete(obj) {
      let success = data => {
        this.$message.success(data.msg);

        if (this.listData.length - 1 === 0) {
          if (this.listParam.page_index > 1) {
            this.listParam.page_index--;
          } else {
            this.listParam.page_index = 1;
          }
        }

        this.getList();
      };

      this.$ajax.delete("api/term/term", {
        params: { password: obj.password },
        func: { success: success }
      });
    },
    isTimeDisabled(time) {
      // if (this.editFlag !== 1 && new Date(time) < new Date()) {
      //     return true;
      // }
    },
    cancel() {
      this.isShowEdit = false;
    },
    /**
     * 1、判断第一学期的开始和结束时间是否大于第二学期的开始时间和结束时间
     * 2、判断第一学期的开始时间是否大于结束时间
     * 3、判断第二学期的开始时间是否大于结束时间
     * 4、判断第一学期的开始时间跟第二学期的结束时间的总天数是否大于一年的天数
     */
    changetime(val, val2) {
      if (
        val === "1" &&
        (this.editForm.secondEndTime || this.editForm.secondStartTime)
      ) {
        if (val2 === "1") {
          if (
            new Date(this.editForm.firstStartTime).getTime() >
              new Date(this.editForm.secondStartTime).getTime() ||
            new Date(this.editForm.firstStartTime).getTime() >
              new Date(this.editForm.secondEndTime).getTime()
          ) {
            this.$message.warning("第一学期的开始时间不能大于第二学期的时间");
            this.editForm.firstStartTime = null;
            this.editForm.firstWeek = 0;
            return false;
          }
        } else {
          if (
            new Date(this.editForm.firstEndTime).getTime() >
              new Date(this.editForm.secondStartTime).getTime() ||
            new Date(this.editForm.firstEndTime).getTime() >
              new Date(this.editForm.secondEndTime).getTime()
          ) {
            this.$message.warning("第一学期的结束时间不能大于第二学期的时间");
            this.editForm.firstEndTime = null;
            this.editForm.firstWeek = 0;
            return false;
          }
        }
      }

      if (
        val === "2" &&
        (this.editForm.firstStartTime || this.editForm.firstEndTime)
      ) {
        if (val2 === "1") {
          if (
            new Date(this.editForm.secondStartTime).getTime() <
              new Date(this.editForm.firstStartTime).getTime() ||
            new Date(this.editForm.secondStartTime).getTime() <
              new Date(this.editForm.firstEndTime).getTime()
          ) {
            this.$message.warning("第二学期的开始时间不能小于第一学期的时间");
            this.editForm.secondStartTime = null;
            this.editForm.secondWeek = 0;
            return false;
          }
        } else {
          if (
            new Date(this.editForm.secondEndTime).getTime() <
              new Date(this.editForm.firstStartTime).getTime() ||
            new Date(this.editForm.secondEndTime).getTime() <
              new Date(this.editForm.firstEndTime).getTime()
          ) {
            this.$message.warning("第二学期的结束时间不能小于第一学期的时间");
            this.editForm.secondEndTime = null;
            this.editForm.secondWeek = 0;
            return false;
          }
        }
      }

      if (
        val === "1" &&
        this.editForm.firstStartTime &&
        this.editForm.firstEndTime
      ) {
        let flag1 =
          new Date(this.editForm.firstStartTime).getTime() >
          new Date(this.editForm.firstEndTime).getTime();
        if (flag1) {
          this.$message.warning("开始时间不能大于结束时间");
          this.editForm.firstWeek = 0;

          if (val2 === "1") {
            this.editForm.firstStartTime = null;
          } else {
            this.editForm.firstEndTime = null;
          }

          return false;
        } else {
          this.editForm.firstWeek = this.getWeeks(
            this.editForm.firstStartTime,
            this.editForm.firstEndTime
          );
          this.$forceUpdate(); //强制渲染
        }
      }

      if (
        val === "2" &&
        this.editForm.secondStartTime &&
        this.editForm.secondEndTime
      ) {
        let flag2 =
          new Date(this.editForm.secondStartTime).getTime() >
          new Date(this.editForm.secondEndTime).getTime();
        if (flag2) {
          this.$message.warning("开始时间不能大于结束时间");
          this.editForm.secondWeek = 0;

          if (val2 === "1") {
            this.editForm.secondStartTime = null;
          } else {
            this.editForm.secondEndTime = null;
          }

          return false;
        } else {
          this.editForm.secondWeek = this.getWeeks(
            this.editForm.secondStartTime,
            this.editForm.secondEndTime
          );
          this.$forceUpdate(); //强制渲染
        }
      }

      if (this.editForm.firstStartTime && this.editForm.secondEndTime) {
        let startTime = new Date(this.editForm.firstStartTime);
        let endTime = new Date(this.editForm.secondEndTime);
        let diff = Math.abs(startTime.getTime() - endTime.getTime());
        let result = parseInt(diff / (1000 * 60 * 60 * 24)) + 1;

        if (result > 365) {
          this.$message.error("两个学期总数相加不得超过365天");
          this.editForm.secondWeek = 0;
          this.editForm.secondEndTime = null;

          return false;
        }
      }
    },
    validatorStart(rule, value, callback) {
      if (value === "") {
        callback(new Error("请选择开始时间"));
      } else {
        callback();
      }
    },
    validatorEnd(rule, value, callback) {
      if (value === "") {
        callback(new Error("请选择结束时间"));
      } else {
        callback();
      }
    },
    // 当前学年的后10个学年
    getYearData() {
      let year = new Date().getFullYear();

      for (let i = 0; i < 10; i++) {
        this.yearData.push({
          label: year + " - " + ++year + " 学年",
          value: i
        });
      }
    },
    // 合并单元格
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 || columnIndex === 5) {
        if (rowIndex % 2 === 0) {
          return {
            rowspan: 2,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
    // 在日期添加几天
    getNewDay(date, day, key) {
      let dateTime = date;
      if (key === 1) {
        dateTime = dateTime.setDate(dateTime.getDate() - day);
      } else {
        dateTime = dateTime.setDate(dateTime.getDate() + day);
      }
      dateTime = new Date(dateTime);
      let time = dateTime.getTime();

      return time;
    },
    // 获取开始日期到结束日期的自然周数,从星期一到星期日为一周
    getWeeks(start, end) {
      let startDate = new Date(start);
      let endDate = new Date(end);

      // 获取当前星期几
      let startDay = startDate.getDay();
      let endDay = endDate.getDay();

      if (startDay === 0) {
        startDay = 6;
      } else {
        startDay = startDay - 1;
      }

      if (endDay === 0) {
        endDay = 0;
      } else {
        endDay = 7 - endDay;
      }

      let startTime = this.getNewDay(startDate, startDay, 1);
      let endTime = this.getNewDay(endDate, endDay, 2);
      let diff = Math.ceil((endTime - startTime) / 1000 / 60 / 60 / 24 / 7);

      return diff;
    },
    handleSizeChange(val) {
      this.listParam.page_index = 1;
      this.listParam.page_size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listParam.page_index = val;
      this.getList();
    }
  }
};
</script>
<style lang="scss">
.term-list {
  .zh-table-contents {
    margin-top: 0;
  }

  .current-year {
    padding-bottom: 20px;
    font-size: 20px;
    font-weight: bold;
  }

  .non-start-year {
    display: flex;
    justify-content: space-between;
    margin-top: 45px;
    padding-bottom: 20px;

    > div:first-child {
      font-size: 20px;
      font-weight: bold;
    }

    > div:last-child {
    }
  }

  .year-title {
    > label {
      font-size: 18px;
      font-weight: bold;
    }

    > div {
      width: 220px;
    }
  }

  .edit-semester-title {
    margin-bottom: 5px;

    > label {
      font-size: 18px;
      font-weight: bold;
    }
  }
}
</style>
